def max_subarray_sum(nums):
    if not nums:
        return 0

    max_current = max_global = nums[0]

    for num in nums[1:]:
        # 要么要么将当前元素加入之前的子数组，要么从当前元素重新开始
        max_current = max(num, max_current + num)
        # 更新全局最大值
        if max_current > max_global:
            max_global = max_current

    return max_global


# 测试案例
test_cases = [
    [1, -2, 3, 5, -1],  # 预期输出: 8
    [1, -2, 3, -8, 5, 1],  # 预期输出: 6
    [1, -2, 3, -2, 5, 1]  # 预期输出: 7
]

for i, case in enumerate(test_cases):
    result = max_subarray_sum(case)
    print(f"测试案例 {i + 1}: {case}: 最大子数组和为 {result}")
